package com.example.todotask.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.todotask.R;
import com.example.todotask.database.DatabaseHandler;
import com.example.todotask.model.Task;
import com.example.todotask.ultils.Constant;

public class TaskListAdapter extends ArrayAdapter<Task> {

	private final Context context;
	private List<Task> tasks;
	private DatabaseHandler db;
	
	static class ViewHolder {
		public CheckBox is_completed;
		public TextView name;
		public View category;
		public ImageView priority;
		public TextView due_date;
	}
	
	public TaskListAdapter(Context context, int textViewResourceId,
			List<Task> objects) {
		super(context, R.layout.item_list_task, objects);
		this.context = context;
		this.tasks = objects;
		setDb(new DatabaseHandler(context));
		setNotifyOnChange(true);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		Task task = tasks.get(position);
		if (view == null && task != null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.item_list_task, null);
			
			// khoi tao cac thanh phan trong list item.
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.name = (TextView) view.findViewById(R.id.text_row_name);
			viewHolder.due_date = (TextView) view.findViewById(R.id.text_row_due_date);
			viewHolder.is_completed = (CheckBox) view.findViewById(R.id.checkbox_row_complete);
			
			// bat sự kiện checkbox.
			viewHolder.is_completed.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
				}
			});
			
			// set thong hien thi tren từng item.
			viewHolder.name.setText(task.getName());
			viewHolder.due_date.setText(task.getDueDate());
			// kiểm tra task hiện tại đã kêt thúc chưa.
			if (task.getCompletion() == Constant.TASK_COMPLETION) {
				// kêt thúc rồi thì đổi background item về màu tối.
				view.setBackgroundResource(android.R.color.holo_orange_dark);
			} else {
				// chưa kết thúc thì màu sáng.
				view.setBackgroundResource(android.R.color.holo_green_light);
			}
		}
 		
		return view;
	}

	public DatabaseHandler getDb() {
		return db;
	}

	public void setDb(DatabaseHandler db) {
		this.db = db;
	}

}
